package com.distribute.application.api.rest.member;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;







import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.distribute.application.api.BaseApiController;
import com.distribute.application.api.utils.Arith;
import com.distribute.application.api.utils.DateUtils;
import com.distribute.application.api.utils.WeiXinAccessTokenUtil;
import com.distribute.application.api.utils.WxMiniQrCodeUtil;
import com.distribute.framework.model.Commodity;
import com.distribute.framework.model.Coupon;
import com.distribute.framework.model.DirectCoupon;
import com.distribute.framework.model.DirectOrder;
import com.distribute.framework.model.HeedCoupon;
import com.distribute.framework.model.InvitCoupon;
import com.distribute.framework.model.InvitRecord;
import com.distribute.framework.model.InvitationQrCode;
import com.distribute.framework.model.Member;
import com.distribute.framework.model.Merchant;
import com.distribute.framework.model.NewGifts;
import com.distribute.framework.model.OfflineCoupon;
import com.distribute.framework.model.OrderDetails;
import com.distribute.framework.model.Parameter;
import com.distribute.framework.model.Product;
import com.distribute.framework.model.RedPacket;
import com.distribute.framework.model.TbMsg;
import com.distribute.framework.model.TbReturnCoupon;
import com.distribute.framework.core.lang.Protocol;
import com.distribute.framework.core.lang.title;
import com.distribute.framework.core.web.helper.Utils;

@RestController(value="api.MemberCouponController")
public class MemberCouponController extends BaseApiController{
	/**
	 * 领取关注有礼优惠卷s
	 * @return
	 */
	@RequestMapping("/api/memberCoupon/getGZCoupons.do")
	public @title("领取关注有礼优惠卷s") Protocol getGZCoupons(
			@title("领取码") String flag
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		HeedCoupon heedCoupon=HeedCoupon.where.accessCode("/pages/member/tab3/coupon/gzcoupon?pmarms="+flag).putIn((short)1).get();
		if (heedCoupon!=null) {
			Coupon coupo=Coupon.where.member(member.getId()).merchant(heedCoupon.getMerchant()).sources((short)4).couponId(heedCoupon.getId()).get();
			Merchant merchant=Merchant.where.id(heedCoupon.getMerchant()).get();
			if (coupo==null) {
				Coupon coupon=new Coupon(
					 	heedCoupon.getDiscount()//折扣 [非空]
					 	,heedCoupon.getMerchant()//所属品牌 [非空]
					 	,heedCoupon.getCommodity()//适用产品 [非空]
					 	,member.getId()//用户 [非空]
					 	,(short)0
					 	,heedCoupon.getExpiryDate()//有效期 [非空]
					 	,(short)4//优惠卷来源
					 	,heedCoupon.getId()//优惠卷ID
					 	,(short)1//使用情况
					 	,new Date()//修改时间 [非空]
					 	,new Date()//添加时间 [非空]
					 	,(short)1//状态 [非空]
						);
				coupon.save();
				TbMsg msg2=new TbMsg(
						member.getId()//会员
						 	,"您获得一张"+heedCoupon.getDiscount()+"折关注优惠券"//内容
						 	,new Date()//时间
							);
           		msg2.save();
				protocol.set("msg", "领取成功  优惠卷已存入您 "+merchant.getBrandName()+"品牌账户中了");
				protocol.set("type", 1);
			}else {
				
				protocol.set("msg", "您已领取过 "+merchant.getBrandName()+"品牌的优惠卷");
				protocol.set("type", 3);
			}
			
		}else {
			protocol.set("msg", "关注有礼优惠卷已关闭");
			protocol.set("type", 3);
		}
		
		return protocol;
	}
	/**
	 * 领取新人礼包
	 * @return
	 */
	@RequestMapping("/api/memberCoupon/getNewCoupons.do")
	public @title("领取关注有礼优惠卷s") Protocol getNewCoupons(
			@title("品牌") Long id
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		NewGifts newGifts=NewGifts.where.id(id).get();
		if (newGifts!=null) {
			Coupon coupo=Coupon.where.member(member.getId()).merchant(newGifts.getMerchant()).sources((short)2).couponId(newGifts.getId()).get();
			Merchant merchant=Merchant.where.id(newGifts.getMerchant()).get();
			if (coupo==null) {
				Coupon coupon=new Coupon(
					 	newGifts.getDiscount()//折扣 [非空]
					 	,newGifts.getMerchant()//所属品牌 [非空]
					 	,newGifts.getCommodity()//适用产品 [非空]
					 	,member.getId()//用户 [非空]
					 	,(short)0
					 	,newGifts.getExpiryDate()//有效期 [非空]
					 	,(short)2//优惠卷来源
					 	,newGifts.getId()//优惠卷ID
					 	,(short)1//使用情况
					 	,new Date()//修改时间 [非空]
					 	,new Date()//添加时间 [非空]
					 	,(short)1//状态 [非空]
						);
				coupon.save();
				TbMsg msg2=new TbMsg(
						member.getId()//会员
						 	,"您获得一张"+newGifts.getDiscount()+"折新人优惠券"//内容
						 	,new Date()//时间
							);
           		msg2.save();
				protocol.set("msg", "领取成功  优惠券已存入您 "+merchant.getBrandName()+"品牌账户中了");
				protocol.set("type", 1);
			}else {
				
				protocol.set("msg", "您已领取过 "+merchant.getBrandName()+"品牌的优惠券");
				protocol.set("type", 3);
			}
			
		}else {
			protocol.set("msg", "新人优惠券已关闭");
			protocol.set("type", 3);
		}
		
		return protocol;
	}
//	/**
//	 * 领取回归优惠券
//	 * @return
//	 */
//	@RequestMapping("/api/memberCoupon/getNewCouponsYQ.do")
//	public @title("领取回归优惠券") Protocol getNewCouponsYQ(
//			@title("品牌") Long id
//			){
//		Protocol protocol = Protocol.create(true, null);
//		Member member=Member.where.uid(this.getUid()).get();
//		if (member==null) {
//			return Protocol.create(false, "操作错误","not_found_user");
//		}
//	    List<TbReturnCoupon> returnCoupons=TbReturnCoupon.where.tbrcMember(this.getUid()).tbrcCoupon(id).tbrcGet((short)1).list(10);
//	    if (returnCoupons.size()>0) {
//			TbReturnCoupon returnCoupon=returnCoupons.get(0);
//			InvitCoupon invitCoupon=InvitCoupon.where.id(id).get();
//			Coupon coupon=new Coupon(
//				 	invitCoupon.getNewDiscount()//折扣 [非空]
//				 	,invitCoupon.getMerchant()//所属品牌 [非空]
//				 	,invitCoupon.getCommodity()//适用产品 [非空]
//				 	,this.getUid()//用户 [非空]
//				 	,(short)0//是否失效
//				 	,invitCoupon.getExpiryDate()//有效期 [非空]
//				 	,(short)3//优惠卷来源
//				 	,invitCoupon.getId()//优惠卷ID
//				 	,(short)1//使用情况
//				 	,new Date()//修改时间 [非空]
//				 	,new Date()//添加时间 [非空]
//				 	,(short)1//状态 [非空]
//					);
//			coupon.save();
//			TbMsg msg2=new TbMsg(
//					member.getId()//会员
//					 	,"您获得一张"+invitCoupon.getNewDiscount()+"折邀请优惠券"//内容
//					 	,new Date()//时间
//						);
//       		msg2.save();
//			returnCoupon.setTbrcGet((short)2);
//			returnCoupon.update();
//			protocol.set("msg", "领取成功  优惠券已存入您 "+invitCoupon.getMerchant$()+"品牌账户中了");
//			protocol.set("type", 1);
//		}else {
//			protocol.set("msg", "您已领取过 该优惠券");
//			protocol.set("type", 3);
//		}
//		return protocol;
//	}
	/**
	 * 会员获取订单可用优惠卷列表
	 * @return
	 */
	@RequestMapping("/api/memberCoupon/getOrderCouponLists.do")
	public @title("会员获取订单可用优惠卷列表") Protocol getOrderCouponLists(
			@title("订单编号") Long orderId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectOrder directOrder=DirectOrder.where.id(orderId).get();
		List<OrderDetails> orderDetails=OrderDetails.where.orders(directOrder.getId()).list(100);
        List<Coupon> coupons=new ArrayList<Coupon>();
		for (OrderDetails orderDetails2 : orderDetails) {
			List<Coupon> couponsA=Coupon.where.member(member.getId()).merchant(directOrder.getMerchant()).isOk((short)0).useStatus((short)1).commodity(orderDetails2.getGoodsNumber()).list(-1);
		       coupons.addAll(couponsA);
		}
		protocol.setList(coupons, new Protocol.BeanFormat<Coupon>(){
			@Override
			public Map format(Coupon t) {
				Map json = t.toJSON();
				Commodity commodity=Commodity.where.id(t.getCommodity()).get();
				json.put("img", commodity.getImage());
				json.put("select", false);
				return json;
			}
		});
		return protocol;
	}
	/**
	 * 会员获取可用优惠卷列表
	 * @return
	 */
	@RequestMapping("/api/memberCoupon/getCouponLists.do")
	public @title("会员获取可用优惠卷列表") Protocol getCouponLists(
			@title("品牌编号") Long banrdId,
			@title("类型") Short type,
			@title("页码") Integer pageNo
			,@title("个数") Integer pageSize
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		Coupon.M where = Coupon.where.member(member.getId()).merchant(banrdId).useStatus(type+1);
		protocol.setPage(where.page(Utils.or(pageNo,0), Utils.or(pageSize,20)), new Protocol.BeanFormat<Coupon>(){
			@Override
			public Map format(Coupon t) {
				Map json = t.toJSON();
				Commodity commodity=Commodity.where.id(t.getCommodity()).get();
				json.put("img", commodity.getImage());
				return json;
			}
		});
		return protocol;
	}
	/**
	 * 会员根据品牌ID获取邀请记录
	 * @return
	 */
	@RequestMapping("/api/memberCoupon/couponListslByBanrdId.do")
	public @title("会员根据品牌ID获取邀请记录") Protocol couponListslByBanrdId(
			@title("品牌编号") Long banrdId,
			@title("页码") Integer pageNo
			,@title("个数") Integer pageSize
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		protocol.setPage(InvitRecord.where.recom(member.getId()).brand(banrdId).page(Utils.or(pageNo,0), Utils.or(pageSize,20)), new Protocol.BeanFormat<InvitRecord>(){
			@Override
			public Map format(InvitRecord t) {
				Map json = t.toJSON();
				Member member=Member.where.uid(t.getInvitedPerson()).get();
				json.put("user", member.toJSON());
				return json;
			}
		});
		return protocol;
	}
	
	/**
	 * 会员获取有奖邀请基础数据
	 * @return
	 */
	@RequestMapping("/api/memberCoupon/getYjyqCouponData.do")
	public @title("会员获取有奖邀请基础数据") Protocol getYjyqCouponData(
			@title("品牌编号") Long banrdId
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		InvitCoupon invitCoupon=InvitCoupon.where.merchant(banrdId).putIn((short)1).get();
		if (invitCoupon!=null) {
			Map map=invitCoupon.toJSON();
			if (invitCoupon.getExpiryDate().getTime()>new Date().getTime()) {
				map.put("days", DateUtils.pastDays(invitCoupon.getExpiryDate()));
			}else {
				map.put("days", -1);
			}
			protocol.set("obj", map);
		}else {
			protocol.set("obj", null);
		}
		if(banrdId!=null){
			Parameter parameter=Parameter.where.merchant(banrdId).get();
			protocol.set("parma", parameter.toJSON());
		}
		return protocol;
	}
	@RequestMapping("/api/memberCoupon/smallProgramCode.do")
	    public @title("获取邀请优惠卷二维码") Protocol smallProgramCode(
	    		@title("品牌编号") Long banrdId
        ){
		Protocol protocol = Protocol.create(true, null);
		 Member member=Member.where.uid(this.getUid()).get();
		 Parameter parameter=Parameter.where.merchant(banrdId).get();
	        //获取律师id
	        String lawyerId = "userId="+member.getId()+"&banrdId="+banrdId;
	        WeiXinAccessTokenUtil weiXinAccessTokenUtil=new WeiXinAccessTokenUtil();
	    	String accessToken=weiXinAccessTokenUtil.getWeChatAccessTokens();
	    	Merchant merchant=Merchant.where.id(banrdId).get();
	    	InvitationQrCode invitationQrCode=InvitationQrCode.where.member(member.getId()).brand(banrdId).get();
	    	String urls="";
	    	if(invitationQrCode!=null){
	    		String fileName=member.getId()+"_"+banrdId+"_"+member.getId()+".png";
	    		String urlString=WxMiniQrCodeUtil.getMiniCode(member.getId()+"_"+banrdId, accessToken,"pages/member/tab3/coupon/couponGet",fileName);
	    		urls=urlString;
	    		invitationQrCode.setCode(urlString);
	    		invitationQrCode.update();
	    	}else {
	    		String fileName=member.getId()+"_"+banrdId+"_"+member.getId()+".png";
	    		String urlString=WxMiniQrCodeUtil.getMiniCode(member.getId()+"_"+banrdId, accessToken,"pages/member/tab3/coupon/couponGet",fileName);
	    		urls=urlString;
	    		InvitationQrCode invitationQrCodes=new InvitationQrCode(
	    				banrdId//所属品牌
	    			 	,member.getId()//所属会员
	    			 	,urlString//二维码
	    			 	,(short)1//类型
	    				);
	    		invitationQrCodes.save();
			}
	    	protocol.set("hb", parameter.getHb());
	    	protocol.set("qrcode", urls);
	    	return protocol;
	    }
	/**
	 * 会员领取定向优惠卷
	 * @return
	 */
	@RequestMapping("/api/memberCoupon/getDCoupon.do")
	public @title("会员领取定向优惠卷") Protocol getDCoupon(
			@title("优惠卷ID") Long id
			
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		DirectCoupon directCoupon=DirectCoupon.where.id(id).get();
		directCoupon.setCount(directCoupon.getCount()-1);
		directCoupon.update();
		Coupon coupon=new Coupon(
			 	directCoupon.getDiscount()//折扣 [非空]
			 	,directCoupon.getMerchant()//所属品牌 [非空]
			 	,directCoupon.getCommodity()//适用产品 [非空]
			 	,member.getId()//用户 [非空]
			 	,(short)0
			 	,directCoupon.getDeadline()//有效期 [非空]
			 	,(short)1//优惠卷来源
			 	,directCoupon.getId()//优惠卷ID
			 	,(short)1//使用情况
			 	,new Date()//修改时间 [非空]
			 	,new Date()//添加时间 [非空]
			 	,(short)1//状态 [非空]
				);
		coupon.save();
		TbMsg msg2=new TbMsg(
				member.getId()//会员
				 	,"您获得一张"+directCoupon.getDiscount()+"折优惠券"//内容
				 	,new Date()//时间
					);
   		msg2.save();
		protocol.set("type", 1);
		protocol.set("msg", "领取成功");
//		int countsx =DirectCoupon.where.id(id).count(1,">").set.count(directCoupon.getCount()-1).update();
//		  if (countsx==1) {
//			Coupon coupon=new Coupon(
//					directCoupon.getTitle()
//				 	,directCoupon.getDiscount()//折扣 [非空]
//				 	,directCoupon.getMerchant()//所属品牌 [非空]
//				 	,directCoupon.getCommodity()//适用产品 [非空]
//				 	,member.getId()//用户 [非空]
//				 	,directCoupon.getDeadline()//有效期 [非空]
//				 	,(short)1//优惠卷来源
//				 	,directCoupon.getId()//优惠卷ID
//				 	,(short)1//使用情况
//				 	,new Date()//修改时间 [非空]
//				 	,new Date()//添加时间 [非空]
//				 	,(short)1//状态 [非空]
//					);
//			coupon.save();
//			protocol.set("type", 1);
//			protocol.set("msg", "领取成功");
//		}else {
//			protocol.set("type", 2);
//			protocol.set("msg", "领取失败");
//		}
		return protocol;
	}
	/**
	 * 会员获取可领取优惠卷列表
	 * @return
	 */
	@RequestMapping("/api/memberCoupon/keCouponLists.do")
	public @title("会员获取可领取优惠卷列表") Protocol keCouponLists(
			@title("品牌编号") Long banrdId
			
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		List<DirectCoupon> diCoupons=DirectCoupon.where.merchant(banrdId).list(1000);
		List<Coupon> coupons=Coupon.where.member(member.getId()).merchant(banrdId).list(1000);
		List<DirectCoupon> list=new ArrayList<DirectCoupon>();
		for (DirectCoupon directCoupon : diCoupons) {
			if(directCoupon.getCount()>0&&directCoupon.getDeadline().getTime()>=new Date().getTime()){
				Boolean isFlag=true;
				for (Coupon coupon : coupons) {
					if (coupon.getSources()==(short)1) {//定向优惠卷
						if (coupon.getCouponId().toString().equals(directCoupon.getId().toString())) {
							isFlag=false;
							break;
						}
					}
				}
				if(isFlag){
					list.add(directCoupon);
				}
			}
		}
		protocol.setList(list, new Protocol.BeanFormat<DirectCoupon>(){
			@Override
			public Map format(DirectCoupon t) {
				Map json = t.toJSON();
				Commodity commodity=Commodity.where.id(t.getCommodity()).get();
				json.put("img", commodity.getImage());
				return json;
			}
		});
		return protocol;
	}
	/**
	 * 会员领取线下优惠卷
	 * @return
	 */
	@RequestMapping("/api/memberCoupon/getLocalCoupon.do")
	public @title("会员领取线下优惠卷") Protocol getLocalCoupon(
			@title("领取码") String codes,
			@title("品牌编号") Long banrdId
			
			){
		Protocol protocol = Protocol.create(true, null);
		Member member=Member.where.uid(this.getUid()).get();
		if (member==null) {
			return Protocol.create(false, "操作错误","not_found_user");
		}
		List<OfflineCoupon> coupons=OfflineCoupon.where.receiveCode(codes).list(1);
		if (coupons.size()==0) {
			protocol.set("type", 4);
			protocol.set("msg", "您的领取码有误");
			return protocol;
		}
		OfflineCoupon coupons2=OfflineCoupon.where.receiveCode(codes).merchant(banrdId).get();
		if (coupons2==null) {
			protocol.set("type", 2);
			protocol.set("msg", "您的领取码不属于当前品牌");
			return protocol;
		}
		if (new Date().getTime()>coupons2.getTermValidity().getTime()) {
			protocol.set("type", 3);
			protocol.set("msg", "领取码已过期");
			return protocol;
		}
		if (coupons2.getReceivingSituation()==(short)2) {
			protocol.set("type", 5);
			protocol.set("msg", "优惠卷已被领取");
			return protocol;
		}
		Coupon coupon=new Coupon(
			 	coupons2.getDiscount()//折扣 [非空]
			 	,coupons2.getMerchant()//所属品牌 [非空]
			 	,coupons2.getCommodity()//适用产品 [非空]
			 	,member.getId()//用户 [非空]
			 	,(short)0
			 	,coupons2.getTermValidity()//有效期 [非空]
			 	,(short)5//优惠卷来源
			 	,coupons2.getId()//优惠卷ID
			 	,(short)1//使用情况
			 	,new Date()//修改时间 [非空]
			 	,new Date()//添加时间 [非空]
			 	,(short)1//状态 [非空]
				);
		 coupon.save();
		 TbMsg msg2=new TbMsg(
					member.getId()//会员
					 	,"您获得一张"+coupons2.getDiscount()+"折线下优惠券"//内容
					 	,new Date()//时间
						);
	   		msg2.save();
				protocol.set("type", 1);
				protocol.set("msg", "领取成功已存入您的优惠卷中");
		return protocol;
	}
}
